package projects.android.sms.activities;

import java.util.ArrayList;

import projects.android.sms.R;
import projects.android.sms.adapter.UserItemAdapter;
import projects.android.sms.db.DBHandle;
import projects.android.sms.encrypter.ObscuredSharedPreferences;
import projects.android.sms.object.NumberHelper;
import projects.android.sms.object.SMS;
import projects.android.sms.object.UserRecord;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.PhoneNumberUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Activity showing the user's inbox.
 * 
 * @author Thomas Jaeger
 * @author Mario Kraml
 * @author Tassilo Posegga
 * @author Robert Schenkenfelder
 * 
 */
public class InboxActivity extends Activity implements OnItemClickListener {

	private ImageButton btLoad;
	private ImageButton btNewMessage;
	private ListView ltSms;
	private ArrayList<UserRecord> users;
	private ArrayList<SMS> sms;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inbox_view);

		btNewMessage = (ImageButton) findViewById(R.id.bt_new_message);
		btNewMessage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), EncryptMySMSActivity.class);
				startActivity(intent);
			}
		});

		btLoad = (ImageButton) findViewById(R.id.bt_load);
		btLoad.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				refresh();
			}
		});

		ltSms = (ListView) findViewById(R.id.lt_sms);

		refresh();

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		if (!prefs.getBoolean("isPasswordSet", false)) {
			showSetPasswordDialog();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {

		final Dialog dialog = new Dialog(InboxActivity.this);
		dialog.setContentView(R.layout.enterpassword_dialog);
		dialog.setTitle("Decrypt message");
		dialog.setCancelable(false);

		Button okButton = (Button) dialog.findViewById(R.id.enterpassword_ok_btn);
		okButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				EditText passwordText = (EditText) dialog.findViewById(R.id.enterpassword_password_et);
				String password = passwordText.getText().toString();
				ObscuredSharedPreferences obscuredPrefs = new ObscuredSharedPreferences(getApplicationContext(),
						PreferenceManager.getDefaultSharedPreferences(getApplicationContext()));
				if (password.equals(obscuredPrefs.getString("pw", "1234"))) {
					String username = users.get(pos).getUsername();
					Intent i = new Intent(getApplicationContext(), UserMessagesActivity.class);
					i.putExtra("username", username);
					startActivity(i);
					dialog.dismiss();

				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.s_passwordnotsafe), Toast.LENGTH_SHORT)
							.show();
				}
			}

		});

		Button cancelButton = (Button) dialog.findViewById(R.id.enterpassword_cancel_btn);
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();

	}

	/**
	 * This method loads all SMS from the database.
	 */
	private void refresh() {

		users = new ArrayList<UserRecord>();
		sms = new ArrayList<SMS>();

		DBHandle db = DBHandle.getInstance(getApplicationContext());
		sms = db.getAllMessages();
		db.close();

		for (int i = 0; i < sms.size(); i++) {
			String username = sms.get(i).getPhonenumber();
			UserRecord u = new UserRecord(username);
			if (getUserIndex(username) == -1) {
				u.addSMS(sms.get(i));
				users.add(u);
			} else {
				u = users.get(getUserIndex(username));
				u.addSMS(sms.get(i));
			}
		}

		if (sms.size() == 0) {
			Toast.makeText(this, "No messages ", Toast.LENGTH_SHORT).show();
		}

		ltSms.setAdapter(new UserItemAdapter(this, android.R.layout.simple_list_item_1, users));
		ltSms.setOnItemClickListener(this);
	}

	private int getUserIndex(String username) {
		for (int i = 0; i < users.size(); i++) {
			if (PhoneNumberUtils.compare(username, users.get(i).getUsername())) {
				return i;
			}
		}
		return -1;
	}

	/**
	 * Shows a dialog prompting the user for setting a password to access his conversations.
	 */
	private void showSetPasswordDialog() {
		// init Dialog
		final Dialog dialog = new Dialog(InboxActivity.this);
		dialog.setContentView(R.layout.setpassword_dialog);
		dialog.setTitle("Please set a password");
		dialog.setCancelable(false);

		Button okButton = (Button) dialog.findViewById(R.id.setpassword_ok_btn);
		okButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				EditText passwordText = (EditText) dialog.findViewById(R.id.setpassword_password_et);
				String password = passwordText.getText().toString();
				EditText confirmPasswordText = (EditText) dialog.findViewById(R.id.setpassword_confirmpassword_et);
				String confirmPassword = confirmPasswordText.getText().toString();

				if (password.length() >= 8 && password.equals(confirmPassword)) {
					Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();

					Editor obscuredEditor = new ObscuredSharedPreferences(getApplicationContext(), PreferenceManager
							.getDefaultSharedPreferences(getApplicationContext())).edit();
					obscuredEditor.putString("pw", password);
					obscuredEditor.commit();
					editor.putBoolean("isPasswordSet", true);
					editor.commit();
					Toast.makeText(getApplicationContext(), "Password set", Toast.LENGTH_SHORT).show();
					dialog.dismiss();

				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.s_passwordnotsafe), Toast.LENGTH_SHORT)
							.show();
				}
			}
		});
		dialog.show();
	}
}
